﻿using Dapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.DepartMentes;
using Management.Systeam.Read.Apis.Application.Command.Resourceses;
using MediatR;
using System.Text;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Resourceses
{
    public class ShowResourcesCommandHandler : IRequestHandler<ShowResourcesCommand, ApiPeaging<ApiResult<List<Resources>>>>
    {
        IBaseRepository<Resources> Resources;
        DatabaseContext db;
        public ShowResourcesCommandHandler(IBaseRepository<Resources> Resources, DatabaseContext db)
        {
            this.Resources = Resources;
            this.db = db;
        }

        public async Task<ApiPeaging<ApiResult<List<Resources>>>> Handle(ShowResourcesCommand request, CancellationToken cancellationToken)
        {
           
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT * FROM Resources");
            sb.Append(" WHERE IsDel LIKE '%" + 0 + "%'");
            if (request.Menu_Code != null)
            {
                sb.Append(" AND Menu_Code LIKE '%" + request.Menu_Code + "%'");
            }
            if (request.Menu_Name != null)
            {
                sb.Append(" AND Menu_Name LIKE '%" + request.Menu_Name + "%'");
            }          
            var paramet = new
            {
                Menu_Code = request.Menu_Code,
                Menu_Name = request.Menu_Name,
                PageSize = request.PageSize,
                offset = (request.PageIndex - 1) * request.PageSize
            };
            var qtlist = await db.DapperConnection.QueryAsync<Resources>(sb.ToString(), paramet);
            int total = qtlist.Count();
            sb.Append(" ORDER BY Menu_Id DESC LIMIT @PageSize OFFSET @offset");

            var pageData = await db.DapperConnection.QueryAsync<Resources>(sb.ToString(), paramet);
            int totalPage = (int)Math.Ceiling(total / (double)request.PageSize);
            return new ApiPeaging<ApiResult<List<Resources>>> 
            {
                Total = total,
                TotalPage = totalPage,
                Data = new ApiResult<List<Resources>>
                {
                    Code = ApiEnum.success,
                    Message = "查询成功",
                    Data = pageData.ToList()
                }
            };
        }
    }
}
